import json
import paho.mqtt.client as mqtt
import time
import threading

class MQTTClient:
    def __init__(self,target_ip,default_port,sub_topic,pub_topic,q_mqtt_data):
        self.client = mqtt.Client()
        self.q_mqtt_data = q_mqtt_data
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.target_ip = target_ip
        self.default_port = default_port
        self.sub_topic = sub_topic
        self.pub_topic = pub_topic
        self.connected = False
        self.connect()
        self.message = ''

    def connect(self):
        try:
            self.client.connect(self.target_ip, self.default_port, 5)
            self.connected = True
            self.client.subscribe(self.sub_topic,qos=0)
            self.client.loop_start()
        except:
            self.connected = False

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            self.connected = True
            print("Connected to MQTT OK!")
        else:
            self.connected = False
            print("Failed to connect, return code %d\n", rc)

    def on_message(self, client, userdata, msg):
        try:
            while not self.q_mqtt_data.empty():
                self.q_mqtt_data.get()
            self.q_mqtt_data.put(json.loads(msg.payload))
        except Exception as e:
            print(e)

    def send_mqtt(self,data):
        if self.connected:
            self.client.publish(self.pub_topic,payload=data,qos=0)
        else:
            print('Not connected to MQTT server. Message not sent.')

    def on_disconnect(self, client, userdata, rc):
        print('Disconnected from MQTT server. Reconnecting...')
        self.connected = False
        threading.Thread(target=self.reconnect)

    def reconnect(self):
        while not self.connected:
            self.connect()
            time.sleep(5)

    def close(self):
        self.client.disconnect()
        self.client.loop_stop()
